import React, {Component} from 'react'
import {fetchData} from '../../../components/AjaxConsumer'
import {
    Form,
    Input,
    Tooltip,
    Icon,
    Row,
    Col,
    Checkbox,
    Button,
    message,
    Modal,
    Radio,
    DatePicker
} from 'antd';
const FormItem = Form.Item;

// 主要表单组件
class SelfForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading : false,
            confirmDirty : false,
            getData : this.props.getData ? this.props.getData: {},
            factoryCode : this.props.factoryCode
        };
        this.uuid = this.props.getData ? this.props.getData.data.length : 0;
    }
    componentDidMount(){
        if(this.state.getData && this.state.getData != {}){
            let length = this.props.getData ? this.props.getData.data.length : 0;
            const data = this.state.getData.data;
            for(let i = 0; i < length; i++){
                let name1 = 'names1_'+i;
                let name2 = 'names2_'+i;
                this.props.form.setFieldsValue({[name1]: data[i].factoryCode});
                this.props.form.setFieldsValue({[name2]:String(data[i].sapFactoryCode)})
            }
        }

    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, fieldsValue) => {
            if (!err) {
                this.setState({loading: true});

                let values = {
                    ...fieldsValue,
                };
                //发送ajax 控制请求数据规则，无值的设为空
                for (let item in values) {
                    if (!values[item]) {
                        values[item] = ''
                    }
                }
                let pstData = [];
                for(let i = 0; i < this.uuid; i++){
                    let tmp = {};
                    let name1 = 'names1_'+i;
                    let name2 = 'names2_'+i;
                    tmp.factoryCode = values[name1];
                    tmp.sapFactoryCode = values[name2];
                    if(tmp.factoryCode != null){
                        pstData.push(tmp);
                    }
                }
                //打印表单提交的值
                console.log('Received values of form: ', pstData);

                //在这里可以改造传给服务器的   values

                const options = {
                    //服务器的url
                    url: '/base/factory/sap/u/' + this.state.factoryCode,
                    type: 'post',
                    condition: JSON.stringify(pstData),//请求条件
                    contentType: 'application/json; charset=utf-8'
                };
                fetchData(this, options, (res) => {
                    //回调函数
                    if (res.code == 1) {
                        message.success('操作成功');
                    }
                    setTimeout(() => {
                        // this.resetFrom();
                        this.props.onCancel();
                        this.setState({loading: false});
                        // console.log("刷新List列表")
                        this.props.refreshHandle();
                    }, 1000); //缓冲

                })
            }
        });
    };
    //减少
    remove = (k) => {
        const { form } = this.props;
        // can use data-binding to get
        const keys = form.getFieldValue('keys');
        // We need at least one passenger
        //if (keys.length === 1) {
        //    return;
        //}

        // can use data-binding to set
        form.setFieldsValue({
            keys: keys.filter(key => key !== k),
        });
    };
    //增加
    add = () => {
        this.uuid++;
        const { form } = this.props;
        // can use data-binding to get
        const keys = form.getFieldValue('keys');
        const nextKeys = keys.concat(this.uuid - 1);
        // can use data-binding to set
        // important! notify form to detect changes
        form.setFieldsValue({
            keys: nextKeys,
        });

    };

    render() {
        const { getFieldDecorator, getFieldValue } = this.props.form;
        const data = this.state.getData.data;
        const colNumber = 12;//一行2个
        const itemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 8 },
            },
            
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
        };
        const formItemLayoutWithOutLabel = {
            wrapperCol: {
                xs: { span: 24, offset: 0 },
                sm: { span: 20, offset: 4 },
            },
        };
        let tempArr = [];
        for (let i = 0; i < this.uuid; i++){
            tempArr.push(i)
        }
        getFieldDecorator('keys', { initialValue: tempArr });
        const keys = getFieldValue('keys');
        const formItems = keys.map((k, index) => {
            return (
                <Row key={k}>
                    <Col span={colNumber}>
                        <FormItem
                            {...itemLayout}
                            label='工厂编码'
                        >
                            {getFieldDecorator(`names1_${k}`, {
                                validateTrigger: ['onChange', 'onBlur'],
                                initialValue: this.state.factoryCode
                            })(
                                <Input disabled="true"/>
                            )}
                        </FormItem>
                    </Col>
                    <Col span={colNumber}>
                        <FormItem
                            {...itemLayout}
                            label='SAP工厂编码'
                        >
                            {getFieldDecorator(`names2_${k}`, {
                                initialValue:'',// data.arr[index]?String(data.arr[index].names2):'',
                                validateTrigger: ['onChange', 'onBlur'],
                                rules: [{
                                    required: true,
                                    whitespace: true,
                                    message: "请填写SAP工厂编码",
                                }],
                            })(
                                <Input placeholder="请填写" style={{ width: '80%', marginRight: 8 }} />
                            )}
                            <Icon
                                className="dynamic-delete-button"
                                type="minus-circle-o"
                                disabled={keys.length === 1}
                                onClick={() => this.remove(k)}
                            />
                        </FormItem>
                    </Col>
                </Row>
            );
        });
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 6}
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 14}
            }
        };
        return (
            <Form
                onSubmit={this.handleSubmit}
                style={{
                backgroundColor: '#fff',
                paddingTop: '20px',
                paddingBottom: '20px'
            }}>
                <div style={{width:'660px',height:'auto',margin:'0 auto'}}>

                    {formItems}
                    <FormItem {...formItemLayoutWithOutLabel}>
                        <Button type="dashed" onClick={this.add} style={{ width: '60%' }}>
                            <Icon type="plus" /> 添加
                        </Button>
                    </FormItem>
                    <div style={{width:'250px', height:'auto', clear:'both', padding:'20px 0', margin:'0px auto'}}>
                        <Button type="primary" htmlType="submit" size="large" >
                            {this.state.loading?'提交中...':'确定'}
                        </Button>
                        <Button
                            type="default"
                            style={{marginLeft: '50px'}}
                            size="large"
                            onClick={()=>this.props.onCancel()}
                        >
                            取消
                        </Button>
                    </div>
                </div>
            </Form>
        );
    }
}
let MyForm = Form.create()(SelfForm);

export default class AsignSapFactory extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            visible: false,
        };

    }
    handleOk = () => {
        // let result = this.state.resData;
        this.setState({
            visible: false,
        });
        this.refreshHandle();
    };

    handleCancel = () => {
        this.setState({
            visible: false,
        });
    };

    refreshHandle = () => {
        console.log("刷新List列表");
        this.props.refreshHandle();
    };

    // (外部调用)
    // 编辑信息
    editHandle = (rowObj) => {
        console.log('rowObj: ', rowObj);
        //根据对象的Id 属性获取对象信息
        let factoryCode = rowObj[0].data.factoryCode;
        this.setState({
            factoryCode: factoryCode
        });
        const options= {
            url: '/base/factory/sap/'+factoryCode,
            type: 'get',//请求方式
            condition:{}
        };
        fetchData(this, options, (resData)=>{
            this.setState({
                resData: resData,
                formTitle: '分配SAP工厂',
                visible: true
            });

        });
    };
    render() {
        return (
            <Modal
                style={{top: '20px'}}
                visible={this.state.visible}
                title={this.state.formTitle ? this.state.formTitle : '填写表单'}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                width={'850px'}
                footer=''
                maskClosable={false}
                key={Math.random()}
            >
                <MyForm
                    getData={this.state.resData}
                    factoryCode={this.state.factoryCode}
                    onCancel={this.handleCancel}
                    refreshHandle = {this.refreshHandle}
                />
            </Modal>
        );
    }
}
